from flask import Blueprint, render_template, request
from flask_login import login_required, current_user
from sqlalchemy import desc, func

from applications.common import curd

from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Device_broken, Device_request, Device, Device_buy, user_role
from datetime import datetime

bp = Blueprint('approve', __name__, url_prefix='/approve')

'''
报废申报页面
'''


# 报废页面, 暂时完成
@bp.get('/broken')
@authorize("system:approve:broken")
def broken():
    return render_template('system/approve/broken_request.html', user=current_user)

def get_current_time():
    create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return datetime.strptime(create_at, "%Y-%m-%d %H:%M:%S")

@bp.post('/broken/submit')
@authorize("system:approve:broken")
def broken_submit():
    req_json = request.get_json(force=True)
    deviceName = str_escape(req_json.get('deviceName'))
    deviceId = str_escape(req_json.get('deviceId'))
    detail = str_escape(req_json.get('detail'))
    producer = str_escape(req_json.get('producer'))
    warranty = str_escape(req_json.get('warranty'))
    username = str_escape(req_json.get('username'))
    userId = str_escape(req_json.get('userId'))
    create_at = get_current_time()
    # 判断当前设备是否存在
    state = curd.get_one_by_id(Device, id=deviceId)
    if state is None:
        return fail_api(msg='设备不存在')
    if state.enable == 0:
        return fail_api(msg='设备已经报废，请勿重复申报')

    broken = Device_broken(
        deviceName=deviceName,
        deviceId=deviceId,
        detail=detail,
        producer=producer,
        warranty=warranty,
        create_at=create_at
    )
    db.session.add(broken)
    db.session.flush()
    device_request = Device_request(
        requesterId=userId,
        requesterName=username,
        type=1,
        formId=broken.id,
        create_at=create_at
    )
    db.session.add(device_request)
    db.session.commit()
    return success_api(msg='提交成功')


'''
采购申报页面
'''


@bp.get('/buy')
@authorize("system:approve:buy")
def buy():
    return render_template('system/approve/buy_request.html')


@bp.post('/buy/submit')
@authorize("system:approve:buy")
def buy_submit():
    req_json = request.get_json(force=True)
    deviceName = str_escape(req_json.get('deviceName'))
    typeNum = str_escape(req_json.get('typeNum'))
    detail = str_escape(req_json.get('detail'))
    producer = str_escape(req_json.get('producer'))
    warranty = str_escape(req_json.get('warranty'))
    create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    create_at = datetime.strptime(create_at, "%Y-%m-%d %H:%M:%S")
    min_money = str_escape(req_json.get('min_money'))
    max_money = str_escape(req_json.get('max_money'))
    username = str_escape(current_user.username)
    userId = str_escape(current_user.id)
    buy = Device_buy(
        deviceName=deviceName,
        producer=producer,
        typeNum=typeNum,
        warranty=warranty,
        create_at=create_at,
        min_money=min_money,
        max_money=max_money,
        detail=detail
    )
    try:
        db.session.add(buy)
        db.session.flush()
        device_request = Device_request(
            requesterId=userId,
            requesterName=username,
            type=2,
            formId=buy.id,
            create_at=create_at
        )
        db.session.add(device_request)
        db.session.commit()
        return success_api(msg='提交成功')
    except:
        return fail_api(msg="字段错误")




'''
审核表页面
'''

@bp.get('/pass')
@authorize("system:approve:pass")
def pass_main():
    return render_template('system/approve/audit.html', user=current_user)


# 审核页面信息分页查询
@bp.get('/pass/data')
@authorize("system:approve:pass")
def data():
    # 获取请求参数
    form_type = str_escape(request.args.get('type', type=str))

    create_at = str_escape(request.args.get('create_at', type=str))
    filters = []
    if form_type:
        filters.append(Device_request.type == form_type)
    if create_at:
        specific_day = datetime.strptime(create_at, '%Y-%m-%d')
        filters.append(func.DATE(Device_request.create_at) == specific_day.date())


    query = db.session.query(
        Device_request
    ).filter(Device_request.status == 0, *filters).layui_paginate()

    return table_api(
        data=[{
            'id': device_request.id,
            'type': device_request.type,
            'status': device_request.status,
            'formId': device_request.formId,
            'create_at': str(device_request.create_at),
            'requesterId': device_request.requesterId,
            'requesterName': device_request.requesterName
        } for device_request in query.items],
        count=query.total)

# 关联改动
def cor_update(device_request):
    if device_request.type == 1:
        res = Device_broken.query.filter_by(id=device_request.formId).first()
        res = Device.query.filter_by(id=res.deviceId).update({"enable": 0})
    # 连接采购表
    elif device_request.type == 2:
        res = 1
    return res

#  通过某个单号
@bp.put('/pass/tools_pass/<int:id>')
@authorize("system:approve:tools_pass", log=True)
def tools_pass(id):
    req_json = request.get_json(force=True)
    reason = str_escape(req_json.get('value'))
    res = Device_request.query.filter_by(id=id).update({"status": 1, "audit_at": get_current_time(), "auditerId": current_user.id, "auditerName": current_user.username, "audit_reason": reason})
    if not res:
        return fail_api(msg="更新失败")
    # 更新设备状态
    device_request = Device_request.query.filter_by(id=id).first()
    # 连接其他表
    res = cor_update(device_request)

    if not res:
        return fail_api(msg="更新失败")
    db.session.commit()
    return success_api(msg="更新成功")


@bp.put('/pass/tools_reback/<int:id>')
@authorize("system:approve:tools_reback", log=True)
def tools_reback(id):
    req_json = request.get_json(force=True)
    reason = str_escape(req_json.get('value'))
    res = Device_request.query.filter_by(id=id).update({"status": 2, "audit_at": get_current_time(), "auditerId": current_user.id, "auditerName": current_user.username, "audit_reason": reason})
    db.session.commit()
    if not res:
        return fail_api(msg="更新失败")
    return success_api(msg="更新成功")

def render_auditDetail_method(device_request):
    if device_request.type == 1:
        device_broken = curd.get_one_by_id(Device_broken, device_request.formId)
        return render_template('system/approve/audit_broken_detail.html', device_broken=device_broken, device_request=device_request)
    elif device_request.type == 2:
        device_buy = curd.get_one_by_id(Device_buy, device_request.formId)
        return render_template('system/approve/audit_buy_detail.html', device_buy=device_buy, device_request=device_request)

@bp.get('/pass/tools_detail/<int:id>')
@authorize("system:approve:tools_detail", log=True)
def detail(id):
    device_request = curd.get_one_by_id(Device_request, id)
    return render_auditDetail_method(device_request)




'''
审核记录总表
'''
@bp.get('/records')
@authorize("system:approve:records")
def records_main():
    return render_template('system/approve/records.html')


# 内容辅助函数
def get_device_request(filters):
    role = db.session.query(user_role).filter_by(user_id=current_user.id).first()
    # 如果是普通用户就只能看自己的申请记录
    if role[-1] == 2:
        query = db.session.query(
            Device_request
        ).filter(Device_request.requesterId == current_user.id and Device_request.status != 0, *filters).layui_paginate()
    else:
        query = db.session.query(
            Device_request
        ).filter(Device_request.status != 0, *filters).layui_paginate()
    return query

@bp.get('/records/data')
@authorize("system:approve:records")
def record_data():
    # 获取请求参数
    form_type = str_escape(request.args.get('type', type=str))

    status = str_escape(request.args.get('status', type=str))
    filters = []
    if form_type:
        filters.append(Device_request.type == form_type)
    if status:
        filters.append(Device_request.status == status)

    query = get_device_request(filters)

    return table_api(
        data=[{
            'id': device_request.id,
            'type': device_request.type,
            'status': device_request.status,
            'formId': device_request.formId,
            'create_at': str(device_request.create_at),
            'audit_at': str(device_request.audit_at),
            'auditerId': device_request.auditerId,
            'auditerName': device_request.auditerName,
            'requesterId': device_request.requesterId,
            'requesterName': device_request.requesterName
        } for device_request in query.items],
        count=query.total)

def render_recordDetail_method(device_request):
    if device_request.type == 1:
        device_broken = curd.get_one_by_id(Device_broken, device_request.formId)
        return render_template('system/approve/record_broken_detail.html', device_broken=device_broken, device_request=device_request)
    elif device_request.type == 2:
        device_buy = curd.get_one_by_id(Device_buy, device_request.formId)
        return render_template('system/approve/record_buy_detail.html', device_buy=device_buy, device_request=device_request)

@bp.get('/records/detail/<int:id>')
@authorize("system:approve:records")
def record_detail(id):
    device_request = curd.get_one_by_id(Device_request, id)
    return render_recordDetail_method(device_request)




